package com.neo.tiny.admin.service.sys.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neo.tiny.admin.entity.sys.SysRole;
import com.neo.tiny.admin.mapper.sys.SysRoleMapper;
import com.neo.tiny.admin.service.sys.SysRoleService;
import com.neo.tiny.common.constant.ErrorCodeConstants;
import com.neo.tiny.common.exception.WebApiException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author yqz
 * @Description
 * @CreateDate 2022/8/8 15:09
 */
@Service
@AllArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    private final SysRoleMapper roleMapper;

    @Override
    public void validRoles(Collection<Long> ids) {
        Assert.notEmpty(ids, "待校验id集合不能为空");
        // 获取角色信息
        List<SysRole> roles = roleMapper.selectBatchIds(ids);

        Map<Long, SysRole> roleMap = roles
                .stream()
                .collect(Collectors.toMap(SysRole::getId, Function.identity(), (key1, key2) -> key1));


        ids.forEach(roleId -> {
            SysRole sysRole = roleMap.get(roleId);
            // 如果根据如参的角色id无法与数据库中的角色匹配，则说明部门不存在
            if (Objects.isNull(sysRole)) {
                throw new WebApiException(ErrorCodeConstants.ROLE_NOT_EXISTS);
            }
        });
    }
}
